import numpy as np
import scipy.optimize as spo
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider, Button, RadioButtons
import matplotlib
matplotlib.rc('xtick', labelsize=24) 
matplotlib.rc('ytick', labelsize=24) 
from matplotlib import patches
matplotlib.rcParams.update({'font.size': 22})

###

E_0 = 1           #Amplitude de l'onde, V/m
c = 1
omega = 1.5          #pulsation
k = omega/c
n1 = 1.2        #Indice propage
n2 = 0.2       #Indice absorb

x1 = np.arange(-10, 0.01, 0.02)        #♣Zone dans l'air
x2 = np.arange(0, 10, 0.02)         #Dielectrique
t0 = 0


def E1(E_0, x1, t) :
    return E_0*np.cos(omega*t-k*x1)
    
def E2(E_0, x2, t, n1, n2) :
    return E_0*np.cos(omega*t-k*n1*x2)*np.exp(-k*n2*x2)
    
def env(E_0, x2, t, n2) :
    return E_0*np.exp(-k*n2*x2)



##Trace onde amortie

s1 = E1(E_0, x1, t0)
s2 = E2(E_0, x2, t0, n1, n2)
env1 = env(E_0, x2, t0, n2)
env2 = -env(E_0, x2, t0, n2)

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.15, bottom=0.25)


f3, = plt.plot(x2, env1, '--r', linewidth = 3)
f4, = plt.plot(x2, env2, '--r', linewidth = 3)
f1, = plt.plot(x1, s1, '-b', linewidth = 4)        #Trace des deux courbes de part et d'autre de l'interface
f2, = plt.plot(x2, s2, '-b', linewidth = 4)
int, = plt.plot([0, 0], [-1.5, 1.5], '-k', linewidth = 2)   #interface
ax.add_artist(patches.Rectangle((0,-1.5), 10, 3, facecolor = 'gray', fill = True, zorder = 0))

ax.text(-3, 1.2, 'Air')
ax.text(1.5, 1.2, 'Diélectrique')



plt.xlabel('$x$ (m)', fontsize = 28)
plt.ylabel('$E$ (V/m)', fontsize = 28)
plt.ylim([-1.5,1.5])
plt.xlim([-10,10])


axt = plt.axes([0.15, 0.11, 0.7, 0.03])
axn1 = plt.axes([0.15, 0.08, 0.7, 0.03])
axn2 = plt.axes([0.15, 0.05, 0.7, 0.03])

st = Slider(axt, 't', 0, 25, valinit=t0, valfmt='%0.1f')        #Slider : t va de 0 a 25
sn1 = Slider(axn1, "n'", 1, 2, valinit=n1, valfmt='%0.2f')        #Slider : n1
sn2 = Slider(axn2, 'n"', 0, 0.5, valinit=n2, valfmt='%0.2f')        #Slider : n2


def update(val):
    tval = st.val
    n1val = sn1.val
    n2val = sn2.val
    f1.set_ydata( E1(E_0, x1, tval) )
    f2.set_ydata( E2(E_0, x2, tval, n1val, n2val) )
    f3.set_ydata( env(E_0, x2, tval, n2val) )
    f4.set_ydata( -env(E_0, x2, tval, n2val) )
    fig.canvas.draw_idle()


st.on_changed(update)
sn1.on_changed(update)
sn2.on_changed(update)

resetax = plt.axes([0.92, 0.08, 0.05, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    st.reset()
button.on_clicked(reset)


mng = plt.get_current_fig_manager()     #Plein ecran
mng.window.showMaximized()
plt.show()



